package com.zlm.custom.spring;

import org.springframework.util.StringUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zlm
 * @date 2025/4/26
 */
public class BeanDefinition {

    private final String name;

    private final Constructor<?> constructor;

    private final Method prosConstrcutMethod;

    private final List<Field> autowiredFields;

    private final Class<?> beanType;

    public BeanDefinition(Class<?> type){
        this.beanType = type;
        Component component = type.getDeclaredAnnotation(Component.class);
        this.name = component.name().isEmpty() ? StringUtils.uncapitalize(type.getSimpleName()) : component.name();
        try {
            this.constructor = type.getConstructor();
            this.prosConstrcutMethod = Arrays.stream(type.getDeclaredMethods()).filter(method -> method.isAnnotationPresent(PostConstruct.class)).findFirst().orElse(null);
            this.autowiredFields = Arrays.stream(type.getDeclaredFields()).filter(field -> field.isAnnotationPresent(Autowired.class)).collect(Collectors.toList());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public String getName(){
        return name;
    }

    public Constructor<?> getConstructor(){
        return constructor;
    }

    public Method getProsConstrcutMethod(){
        return prosConstrcutMethod;
    }

    public List<Field> getAutowiredFields(){
        return autowiredFields;
    }

    public Class<?> getBeanType() {
        return beanType;
    }
}
